package com.example.blog.controller;

import com.example.blog.config.page.PageRequest;
import com.example.blog.config.page.PageResult;
import com.example.blog.entity.Category;
import com.example.blog.service.CategoryService;
import com.example.blog.util.JsonResult;
import com.example.blog.util.PageUtil;
import com.example.blog.util.Result;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

/**
 * @Author: lu
 * @Date: 2023-09-09-13:46
 * @Description: 分类管理接口
 */
@Api(tags = "分页功能")
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    /**
     *  分页查询
    * @param
    * @return
    */

    @ApiOperation(value = "分页查询")
    @PostMapping("list")
    public Result<Object> ListPage(@RequestBody @Valid PageRequest pageRequest){
        List<Category> categoryList = categoryService.getCategoryPage(pageRequest);
        PageInfo pageInfo = new PageInfo(categoryList);
        PageResult pageResult = PageUtil.getPageResult(pageRequest, pageInfo);
        return Result.success(pageResult);
    }

    /**
     * 添加分类
     * @return
     */
    @ApiOperation(value = "添加分类")
    @PostMapping("/create")
    public Result<Object> categoryCreate(@RequestBody @Valid Category category) {
        int isStatus = categoryService.saveCategory(category);
        if (isStatus == 0) {
            return Result.error("添加分类失败");
        }
        return Result.success();
    }


    /**
     * 修改分类
     * @param category
     * @return
     */
    @ApiOperation(value = "修改分类")
    @PostMapping("/update")
    public Result<Object> categoryUpdate(@RequestBody @Valid Category category) {
        int isStatus = categoryService.updateCategory(category);
        if (isStatus == 0) {
            return Result.error("修改分类失败");
        }
        return Result.success();
    }

    /**
     * 删除分类
     * @param categoryId
     * @return
     */
    @ApiOperation(value = "删除分类")
    @PostMapping("/delete/{id}")
    public Result<Object> categoryDelete(@PathVariable("id") int categoryId) {
        categoryService.deleteCategory(categoryId);
        return Result.success();
    }

    /**
     * 根据id获取分类
     * @param categoryId
     * @return
     */
    @ApiOperation(value = "根据id获取分类")
    @PostMapping("/list/{id}")
    public Result<Object> categoryGetById(@PathVariable("id") int categoryId) {
        List<Category> category = categoryService.findById(categoryId);
        return Result.success(category);
    }

}
